#include "config.h"

#ifdef ENABLE_MYSQL
#include <iostream>

#if (defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(_WIN64) || defined(WIN64))
#include <winsock2.h>
#include <windows.h>
#endif

#include <mysql.h>

#include "MySQLDatabase.h"
#include "MySQLQuery.h"

/**
 *
 **/
MySQLQuery::MySQLQuery(MySQLDatabase *dbc, PString database, PString sqlQuery) : AbstractQuery(dbc, database, sqlQuery) {
    this->result = NULL;

    boost::mutex::scoped_lock lock( dbc->queryLock );

    if (mysql_query(dbc->conn, sqlQuery->c_str())) {
		std::cout << "Query: " << sqlQuery->c_str() << std::endl;
		std::cout << "error: " << mysql_error(dbc->conn) << std::endl;
		std::cout << std::endl;
	}
	else
	{
        this->result = mysql_store_result(dbc->conn);
        if(this->result != NULL) this->num_rows = mysql_num_rows(this->result);
		else this->num_rows = 0;
	}
	lock.unlock();
}

/**
 *
 **/
MySQLQuery::~MySQLQuery(){
    if(this->result != NULL)
        mysql_free_result(this->result);
}

/**
 *
 **/
PDataRow MySQLQuery::fetch() {
	MYSQL_ROW row = mysql_fetch_row(this->result);
	MYSQL_FIELD* fields = mysql_fetch_fields(this->result);

	unsigned int column_count = mysql_num_fields(this->result);
	for(unsigned int i=0;i < column_count; i++)
	{
		this->datarow->put(fields[i].name, row[i]);
	}
	return this->datarow;
}

#endif